package com.cn.wanxi.servlet;

import com.alibaba.fastjson.JSONObject;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.IUserService;
import com.cn.wanxi.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//乱码处理
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        //        1.接受页面数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        String phone = req.getParameter("phone");
        String sex = req.getParameter("sex");
        String birthday = req.getParameter("birthday");
        String hobby = req.getParameter("hobby");
        hobby = hobby.replace("[", "").replace("]", "");
        hobby = hobby.replace("\"", "");
        String introduce = req.getParameter("introduce");
        String sessionCode = (String) req.getSession().getAttribute("code");
//        2.封装页面数据
        UserModel userModel = new UserModel();
        userModel.setUsername(username);
        userModel.setPassword(password);
        userModel.setCode(code);
        userModel.setSex(sex);
        userModel.setPhone(phone);
        userModel.setBirthday(birthday);
        userModel.setHobby(hobby);
        userModel.setIntroduce(introduce);
        userModel.setSessionCode(sessionCode);
//        3.调用服务逻辑层
        IUserService iUserService = new UserServiceImpl();
        String result = iUserService.add(userModel);
//        4.得到返回结果
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", result);
        resp.getWriter().println(jsonObject);
//        String result = iUserService.add(userModel);
        //        5.转发数据转发页面
//        if (result) {
//            req.getRequestDispatcher("/html/login.html").forward(req, resp);
//        } else {
//            req.getRequestDispatcher("/html/userRegiter.html").forward(req, resp);
//        }

    }
    /**
     * 1.servlet  接收ajax传递过来的值
     *  1）乱码处理
     *  2）拿值
     *  3）封装model
     *  4）调用逻辑层
     *  5）得到数据
     *  6）返回结果
     * 2.service  调用数据层
     *  1.判断验证码
     *  2.判断用户名是否存在
     *  3.新增用户
     * 3.dao   数据实现层
     *  1.sql语句的编写
     *  2.调用jdbc
     *  3.返回结果
     * 4.jdbc手写代码
     */
}
